<template>
  <div class="content">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="130px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属学校" prop="deptId">
            <el-select
              v-model="ruleForm.deptId"
              :disabled="userInfo.deptId!=null"
              placeholder="请选择学校"
              clearable
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in schoolList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="食堂名称" prop="name">
            <el-input class="title" v-model="ruleForm.name" placeholder="请输入食堂名称" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="食堂责任人" prop="cadre">
            <el-input class="title" v-model="ruleForm.cadre" placeholder="请输入食堂责任人" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="食堂责任人电话" prop="cadrePhone">
            <el-input
              class="title"
              v-model="ruleForm.cadrePhone"
              placeholder="请输入食堂责任人电话"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="食堂电话" prop="phone">
            <el-input class="title" v-model="ruleForm.phone" placeholder="请输入食堂电话" clearable></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="食堂地址" prop="address">
            <el-input class="title" v-model="ruleForm.address" placeholder="请输入食堂地址" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="食堂管理员账号" prop="sysUserName">
            <el-input class="title" v-model="ruleForm.sysUserName" placeholder="请输入食堂管理员账号" clearable></el-input>
          </el-form-item>
        </el-col>

      </el-row>
      <template>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column prop="name" label="名称" width="180"></el-table-column>
          <el-table-column prop="date" label="开始时间">
            <template slot-scope="scope">
              <el-time-picker
                v-model="timeData['AStartTime-'+scope.$index]"
                size="mini"
                placeholder="开始时间"
              ></el-time-picker>
            </template>
          </el-table-column>
          <el-table-column prop="date" label="结束时间">
            <template slot-scope="scope">
              <el-time-picker
                v-model="timeData['BEndenTime-'+scope.$index]"
                size="mini"
                placeholder="结束时间"
              ></el-time-picker>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <el-form-item style="margin-top: 20px">
        <el-button @click="resetForm('ruleForm')">{{$t("action.reset")}}</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">{{$t("action.save")}}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import Cookies from "js-cookie";
  import {format} from "@/utils/datetime";

  export default {
    name: "edit",
    props: {
      msg: ""
    },
    data() {
      return {
        url: this.$Config.url,
        id: "",
        userInfo: {},
        schoolList: [], //学校数据
        timeData: {
          "AStartTime-0": "09:36",
          "AStartTime-1": "09:36",
          "AStartTime-2": "09:36",
          "BEndenTime-0": "09:36",
          "BEndenTime-1": "09:36",
          "BEndenTime-2": "09:36"
        }, //选择时间列表
        fade: {},
        radio: "", //选择每天相同和每天不同
        ruleForm: {
          address: "", //食堂地址
          breakfastTime: "", //早餐时间段，例子：6:30-9:30
          cadre: "", //食堂负责人
          cadrePhone: "", //食堂负责人电话
          deptId: "", //机构ID
          dinnerTime: "", //晚餐时间段，例子：6:30-9:30
          id: "",
          lunchTime: "", //午餐时间段，例子：6:30-9:30
          name: "", //食堂名称
          phone: "", //食堂电话
          sysUserName:"",//食堂管理员账号
        },
        rules: {
          name: [
            {required: true, message: "请输入食堂名称", trigger: "blur"},
            {min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur"}
          ],
          phone: [{required: true, message: "请输入食堂电话", trigger: "blur"}],
          address: [
            {required: true, message: "请输入食堂地址", trigger: "blur"}
          ],
          sysUserName: [
            {required: true, message: "请输入食堂管理员账号", trigger: "blur"}
          ],
          cadre: [
            {required: true, message: "请输入食堂负责人", trigger: "blur"}
          ],
          cadrePhone: [
            {required: true, message: "请输入食堂负责人电话", trigger: "blur"}
          ],
          deptId: [{required: true, message: "请选择学校", trigger: "change"}]
        },
        tableData: [
          {
            name: "早餐"
          },
          {
            name: "午餐"
          },
          {
            name: "晚餐"
          }
        ]
      };
    },
    mounted() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.userInfo = userInfo;
      this.getSchool();
    },
    methods: {
      getSchool() {
        const that = this;
        const userInfo = JSON.parse(localStorage.getItem("userInfo"));
        this.$axios
          .get(that.url + "/admin/dept/list", {
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          })
          .then(function (res) {
            if (res.data.code == 200) {
              that.schoolList = res.data.data;

              if (!!userInfo.deptId == false) {
              } else {
                that.ruleForm.deptId = userInfo.deptId;
              }
            } else {
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      resetData(id = 1) {
        this.$refs["ruleForm"].resetFields();//先清空
        const that = this;
        this.getSchool();
        if (id) {
          this.id = id;
        }
        this.$axios
          .get(that.url + "/admin/market/get/{id}", {
            params: {
              id
            },
            headers: {
              "x-baie-admin-token": Cookies.get("token")
            }
          })
          .then(function (res) {
            if (res.status == 200) {
              let data = res.data.data;
              // breakfastTime.slice(0,4)
              // lunchTime
              // dinnerTime

              that.timeData = {
                "AStartTime-0": data.breakfastTime ? new Date(
                  "2019/02/03 " +
                  data.breakfastTime.slice(0, 5).toString() +
                  ":00"
                ) : "",
                "AStartTime-1": data.lunchTime ? new Date(
                  "2019/02/03 " + data.lunchTime.slice(0, 5).toString() + ":00"
                ) : "",
                "AStartTime-2": data.dinnerTime ? new Date(
                  "2019/02/03 " + data.dinnerTime.slice(0, 5).toString() + ":00"
                ) : "",
                "BEndenTime-0": data.breakfastTime ? new Date(
                  "2019/02/03 " +
                  data.breakfastTime.slice(6, 11).toString() +
                  ":00"
                ) : "",
                "BEndenTime-1": data.lunchTime ? new Date(
                  "2019/02/03 " + data.lunchTime.slice(6, 11).toString() + ":00"
                ) : "",
                "BEndenTime-2": data.dinnerTime ? new Date(
                  "2019/02/03 " + data.dinnerTime.slice(6, 11).toString() + ":00"
                ) : ""
              };

              that.ruleForm = data;
              that.id = data.id;
            } else {
              that.$message({
                message: res.data.msg,
                type: "warning"
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      submitForm(formName) {
        const that = this;
        this.$refs[formName].validate(valid => {
          if (valid) {
            that.send();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      send() {
        const that = this;
        let zao = [];
        let zhong = [];
        let wan = [];

        for (let i in this.timeData) {
          let time = new Date(this.timeData[i]);

          if (i.slice(0, 10) === "AStartTime") {
            //开始时间
            if (i.slice(11, 12) == 0) {
              //早
              zao.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            } else if (i.slice(11, 12) == 1) {
              //中
              zhong.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            } else {
              //晚
              wan.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            }
          } else if (i.slice(0, 10) === "BEndenTime") {
            //结束时间
            if (i.slice(11, 12) == 0) {
              //早
              zao.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            } else if (i.slice(11, 12) == 1) {
              //中
              zhong.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            } else {
              //晚
              wan.push(
                (time.getHours() < 10 ? "0" + time.getHours() : time.getHours()) +
                ":" +
                time.getMinutes()
              );
            }
          }
        }


        this.ruleForm.breakfastTime =
          zao.length == 0 ? "" : (zao[0] == "NaN:NaN" ? '' : zao[0]) + (zao[0] == "NaN:NaN" || zao[1] == "NaN:NaN" ? "" : "-") + (zao[1] == "NaN:NaN" ? '' : zao[1]);
        this.ruleForm.lunchTime =
          zhong.length == 0 ? "" : (zhong[0] == "NaN:NaN" ? '' : zhong[0]) + (zhong[0] == "NaN:NaN" || zhong[1] == "NaN:NaN" ? "" : "-") + (zhong[1] == "NaN:NaN" ? '' : zhong[1]);
        this.ruleForm.dinnerTime = wan.length == 0 ? "" : (wan[0] == "NaN:NaN" ? '' : wan[0]) + (wan[0] == "NaN:NaN" || wan[1] == "NaN:NaN" ? "" : "-") + (wan[1] == "NaN:NaN" ? '' : wan[1]);

        // this.ruleForm.sysUserName = sessionStorage.getItem("name");
        console.log(this.ruleForm)

        this.$axios
          .post(
            that.url + "/admin/market/saveOrUpdate",
            that.$qs.stringify(that.ruleForm),
            {
              headers: {
                "x-baie-admin-token": Cookies.get("token")
              }
            }
          )
          .then(function (res) {
            if (res.status == 200) {
              if (res.data.code == 200) {
                if (that.msg == 1) {
                  that.$message({
                    message: "添加成功",
                    type: "success"
                  });
                } else {
                  that.$message({
                    message: "修改成功",
                    type: "success"
                  });
                }
                that.$emit("hideEdit", false);
              } else {
                that.$message({
                  message: res.data.msg,
                  type: "warning"
                });
              }

            } else {
              that.$message({
                message: res.statusText,
                type: "warning"
              });
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
        this.getSchool();
        this.ruleForm.id = "";
        for (let key in this.timeData) {
          this.timeData[key] = "";
        }
      }
    }
  };
</script>

<style scoped lang="scss">
  .everyDaySame {
    display: flex;
    border: 1px solid #ebeef5;
    margin: 15px 0;

    p {
      width: 50px;
      padding-left: 20px;
    }
  }

  .content {
    padding: 0 5%;
  }

  .title {
    width: 50%;
  }

  .el-select,
  .el-input {
    width: 100%;
  }

  .el-table {
    margin-top: 15px;
  }

  .el-date-editor {
    width: 100%;
  }
</style>
